import json

from django.forms import model_to_dict
from django.http import HttpResponse
from django.shortcuts import render

from entity.common.response import ResponseData, ResponseStatus
from goodsApp.service.collectionService import CollectionService
from utils.transfer import transferToJson

colService = CollectionService()

def addGoods(request):
    gid = request.GET.get('id')
    user = json.loads(request.session['user'])
    uid = user['id']
    result = colService.addGoods(uid,gid)
    response = ResponseData(success=True,responseCode=ResponseStatus.SUCESS,message=result)
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)
def removeGoods(request):
    user = json.loads(request.session['user'])
    uid = user['id']
    gid = request.GET.get('id')
    colService.removeGoods(user_id=uid,goods_id=gid)
    response = ResponseData(success=True,responseCode=ResponseStatus.SUCESS)
    return HttpResponse(content=transferToJson(response),content_type=ResponseData.JSON_CONTENT_TYPE)
def getGoods(request):
    user = request.session['user']
    if user==None:
        return render(request,"login.html")
    user = json.loads(user)
    cur = request.GET.get('page',1)
    size = request.GET.get('size',1)
    glist = colService.getGoods(user_id=user['id'],cur=cur,size=size)
    result = []
    for g in glist:
        result.append(g)
    response = ResponseData(success=False,responseCode=ResponseStatus.SUCESS,data=result)
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)


